import json
from django.views import View
from django.http.response import JsonResponse
from casedemo10_drf.serializers import StudentModelSerializer,Student1SerializerDemo2
from rest_framework.viewsets import ModelViewSet
from casedemo10_drf.models import Student
# Create your views here.
'''
序列化视图类
'''
class Student1View(View):
    """序列化器"""
    def get1(self, request):
        """序列化一个模型对象"""
        # 1. 获取数据集
        student = Student.objects.first()
        # 2. 实例化序列化器，获取序列化对象
        serializer = Student1SerializerDemo2(student)
        # 3. 调用序列化对象的data属性方法获取转换后的数据
        data = serializer.data
        # 4. 响应数据
        return JsonResponse(data=data, status=200, safe=False, json_dumps_params={"ensure_ascii": False})

    def get(self, request):
        """反序列化-采用字段选项来验证数据集"""
        # 1. 接收客户端提交的数据
        # data = json.dumps(request.body)
        # 模拟来自客户端的数据
        data = {
            "name": "xiaoming",
            "age": 117,
            "sex": True,
            "classmate": "301",
            "description": "这家伙很懒，什么都没有留下~"
        }
        # 1.1 实例化序列化器，获取序列化对象
        serializer = Student1SerializerDemo2(data=data)
        # 1.2 调用序列化器进行数据验证
        ret = serializer.is_valid()  # 不抛出异常
        # ret = serializer.is_valid(raise_exception=True)  # 抛出异常
        print(f"ret={ret}")
        # 1.3 获取验证以后的结果
        if ret:
            return JsonResponse(dict(serializer.validated_data))
        else:
            return JsonResponse(dict(serializer.errors))
        # 2. 操作数据库
        # 3. 返回结果